package red.yancloud.www.ui.activity

import android.util.Log
import android.view.KeyEvent
import android.view.View
import androidx.appcompat.widget.LinearLayoutCompat
import androidx.viewpager.widget.ViewPager
import com.alibaba.fastjson.JSONObject
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_main.*
import okhttp3.ResponseBody
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import red.yancloud.www.R
import red.yancloud.www.base.BaseActivity
import red.yancloud.www.common.Constants
import red.yancloud.www.common.MessageEvent
import red.yancloud.www.db.sharedpreference.UserInfoShardPreference
import red.yancloud.www.internet.api.RedCloudApis
import red.yancloud.www.internet.bean.Login
import red.yancloud.www.manager.AppManager
import red.yancloud.www.ui.adapter.ViewPagerFragmentAdapter
import red.yancloud.www.ui.fragment.*
import red.yancloud.www.util.AppUtils
import red.yancloud.www.util.ToastUtils
import java.util.ArrayList

/**
 * @Org：www.shuhai.com(陕西书海网络科技有限公司)
 * @Author：风不会停息 on 2019/5/31 9:50
 * E_Mail：yh131412hys@163.com
 * Describe：主页面
 * Change：
 * @Version：V1.0
 */
class MainActivity : BaseActivity(), View.OnClickListener {

    private val TAG = "MainActivity"

    private val linearLayoutCompats = ArrayList<LinearLayoutCompat>()
    private lateinit var mineFragment:MineFragment

    override val layoutId: Int
        get() = R.layout.activity_main

    override fun initData() {

        AppManager.getAppManager().addActivity(this)

        EventBus.getDefault().register(this)

        if (UserInfoShardPreference.instance.isLogin) {

            RedCloudApis.getInstance().userInfo(UserInfoShardPreference.instance.uid,object :Observer<ResponseBody>{
                override fun onComplete() {
                }

                override fun onSubscribe(d: Disposable) {
                }

                override fun onNext(t: ResponseBody) {

                    val result = String(t.bytes())
                    Log.d(TAG, result)
                    val jsonObject = JSONObject.parseObject(result) ?: return
                    val code = jsonObject.getString("code")

                    Log.d(TAG, jsonObject.toString())

                    if (code==Constants.SYSTEM_OK) {

                        val loginEntity = JSONObject.parseObject(result, Login::class.java)
                        UserInfoShardPreference.instance.saveUserInfo(loginEntity.data)
                    }else{

                        ToastUtils.showToast(jsonObject.getString("msg"))
                    }
                }

                override fun onError(e: Throwable) {
                }
            })
        }

        for (mainMenu in intArrayOf(R.id.mainActivity_menu_home, R.id.mainActivity_menu_sort,
            R.id.mainActivity_menu_repository, R.id.mainActivity_menu_read, R.id.mainActivity_menu_mine)) {

            linearLayoutCompats.add(findViewById(mainMenu))
            findViewById<LinearLayoutCompat>(mainMenu).setOnClickListener(this)
        }
        setButtonStatue(0)

        val adapter = ViewPagerFragmentAdapter(supportFragmentManager)
        adapter.addFragment(HomeFragment())
        adapter.addFragment(SortFragment())
        adapter.addFragment(RepositoryFragment())
        adapter.addFragment(ReadFragment())
        mineFragment = MineFragment()
        adapter.addFragment(mineFragment)
//        预加载页数，处理无法保存Fragment状态异常
        mainActivity_vP.offscreenPageLimit=4
        mainActivity_vP.adapter = adapter
        mainActivity_vP.addOnPageChangeListener(object :ViewPager.OnPageChangeListener{
            override fun onPageScrollStateChanged(state: Int) {
            }

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
            }

            override fun onPageSelected(position: Int) {

                setButtonStatue(position)
                if (position==Constants.RedCloudMainType.MAIN_REPOSITORY_VIEW) {
                    mainActivity_menu_repository_small_iv.visibility=View.GONE
                    mainActivity_menu_repository_big_iv.visibility=View.VISIBLE
                }else{
                    mainActivity_menu_repository_small_iv.visibility=View.VISIBLE
                    mainActivity_menu_repository_big_iv.visibility=View.GONE
                }
            }
        })
    }

    override fun configViews() {
    }

    private fun setButtonStatue(btnStatue: Int) {

        for (i in linearLayoutCompats.indices) {
            linearLayoutCompats[i].isSelected = btnStatue == i
        }
    }

    override fun onClick(v: View?) {
        when (v!!.id) {
            /**
             * 主页面切换
             */
            R.id.mainActivity_menu_home -> mainActivity_vP.currentItem = Constants.RedCloudMainType.MAIN_HOME_VIEW
            R.id.mainActivity_menu_sort -> mainActivity_vP.currentItem = Constants.RedCloudMainType.MAIN_SORT_VIEW
            R.id.mainActivity_menu_repository -> mainActivity_vP.currentItem = Constants.RedCloudMainType.MAIN_REPOSITORY_VIEW
            R.id.mainActivity_menu_read -> mainActivity_vP.currentItem = Constants.RedCloudMainType.MAIN_READ_VIEW
            R.id.mainActivity_menu_mine -> mainActivity_vP.currentItem = Constants.RedCloudMainType.MAIN_MINE_VIEW
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {

        var flag = true

        if (keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_DOWN) {
            if (!isFinishing) {
                AppUtils.Exit(this)
            }
        }else {
            flag = super.onKeyDown(keyCode, event)
        }
        return flag
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event:MessageEvent){

//        when (event.type) {
//            Constants.REFRESH_MINE_FRAGMENT-> {
//                Log.d(TAG,event.type.toString())
//                mineFragment.setUserInfo(event.result as Login.DataBean)
//            }
//            else -> {
//            }
//        }
    }
}
